from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from rest_framework_simplejwt.views import TokenViewBase
from movie.utils.Authentication import MyTokenObtainPairSerializer
from rest_framework.views import APIView
from recommand_demo.serializers import LoginSerializer


# 登录
class LoginView(TokenViewBase):
    # simplejwt token颁发
    serializer_class = MyTokenObtainPairSerializer
    def post(self,request):
        print(request.data)
        serializer =self.get_serializer(data=request.data)
        if serializer.is_valid():
            return Response(serializer.validated_data,status=status.HTTP_200_OK)
        else:
            return Response(status=status.HTTP_401_UNAUTHORIZED)


from captcha.views import CaptchaStore, captcha_image
import base64
# 图片验证码
class CaptchaAPIView(APIView):
    def get(self, request):
        hashkey = CaptchaStore.generate_key()
        id = CaptchaStore.objects.filter(hashkey=hashkey).first().id
        imgage = captcha_image(request, hashkey)
        # 将图片转换为base64
        image_base = base64.b64encode(imgage.content)
        json_data = {
            "key": id,
            "image_base": "data:image/png;base64," + image_base.decode('utf-8'),
            'code': 2000,
            'msg': '获取成功'
        }
        return Response(data=json_data)

from movie.tasks import sms_phone_c
import random
# 注册
@api_view(['POST'])
def get_mobile_code(request):
    print(request.data)
    mobile = request.data['mobile']
    code = random.randrange(1000, 9999)
    cache_key = 'sms_%s' % (mobile)
    cache.set(cache_key, code, 60)
    # 添入celery
    sms_phone_c.delay(mobile,code)
    print('经过这里')
    # {'PhoneNumbers': '19959797519',
    # 'SignName': '阿里云短信测试',
    # 'TemplateCode': 'SMS_154950909',s
    # 'TemplateParam': '{"code":"9605"}'}
    # print(code)
    # 将验证码写进redis缓存
    result = {
        'code': 2000,
        'msg': '发送验证码成功,请在1分钟内写入'
    }
    return Response(data=result, status=status.HTTP_200_OK)

from django.core.cache import cache
# 注册
@api_view(['POST'])
def CustomRegister(request):
    get_message = request.data
    # 测试号码 19959797519
    mobile = get_message['mobile']
    mobile_captcha = get_message['mobile_captcha']
    print(mobile,mobile_captcha)
    cache_key = 'sms_%s' % (mobile)
    code = cache.get(cache_key)
    print(code)
    if code==None:
        result = {
            'code':4000,
            'msg':'验证码不存在，请重新发送'
        }
        return Response(result,status=status.HTTP_404_NOT_FOUND)
        if get_message['mobile_captcha'] != code:
            result = {
                'code':4000,
                'msg': '验证码验证不成功'
            }
            return Response(result,status=status.HTTP_404_NOT_FOUND)
    serializer = LoginSerializer(data=get_message, partial=True)
    if serializer.is_valid(raise_exception=True):
        serializer.save()
        result = {
            'code': 2000,
            'msg': '注册成功'
        }
        return Response(status=status.HTTP_200_OK, data=result)
    return Response({"msg": '出了点问题噢!!!'}, status=status.HTTP_400_BAD_REQUEST, )